﻿// Copyright 2008 Figbrain
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core.Logging;
using IBatisNet.DataMapper;
using Castle.Facilities.IBatisNetIntegration;
using Nextworks.Core.Plugin;

namespace Nextworks.Core.Persistence
{
    internal class PersistentItemServiceImpl : IPersistentItemService
    {
        private ILogger logger = NullLogger.Instance;

        public ILogger Logger
        {
            get { return logger; }
            set { logger = value; }
        }

        public IPluginService PluginService { get; set; }
        public ISqlMapper SqlMap {get; set;}

        public PersistentItem CreateItem(String typeKey)
        {
            PluginDataObject dataObject = PluginService.GetObject(typeKey);
            Type type = dataObject.ObjectType;

            PersistentItem item = (PersistentItem)Activator.CreateInstance(type);
            item.Id = Guid.NewGuid();
            item.ObjectType = typeKey;
            item.CurrentVersion = 0;
            item.CreationDate = item.ModificationDate = DateTime.Now;
            item.IsDeleted = false;

            return item;
        }

        public PersistentItem LoadItem(Guid id)
        {
            throw new NotImplementedException();
        }

        public void SaveItem(PersistentItem item)
        {
            PluginDataObject dataObject = PluginService.GetObject(item.ObjectType);
            SqlMap.Update("item.save", item);
            dataObject.Plugin.Mapper.Update(item.ObjectType + ".save", item);
        }

        public void DeleteItem(PersistentItem item)
        {
            SqlMap.Delete("item.delete", item);
        }
    }
}
